import serial
import json

DEVICE_PATH = '/dev/ttyACM0'
LCD_W = 320
LCD_H = 240

# 16-bit color
COLOR_YELLOW = 0xFFE0
COLOR_GREEN = 0x07E0
COLOR_PURPLE = 0xF81F
COLOR_BLACK = 0x0000
COLOR_WHITE = 0xFFFF

FLAG_OLED = 4

ser = serial.Serial(DEVICE_PATH, 115200)



def drainReadBuffer():
    # Read all from device, return immediately when no more data
    if ser.in_waiting == 0:
        return
    bs = ser.read_all()
    print('[lcd] log:', bs.strip().decode('utf-8'))
    return

def writeObj(o):
    drainReadBuffer()
    ser.write(json.dumps(o, ensure_ascii=True).encode('utf-8'))
    ser.write(b'\n')


def clear(fl = 0):
    writeObj({
        'f': 1 + fl,
    })

def drawTitle(title, fgColor=COLOR_BLACK, bgColor=COLOR_YELLOW):
    writeObj({
        'f': 2,
        'x': 0,
        'y': 0,
        'w': LCD_W,
        'h': 30,
        'fg': bgColor,
    })
    writeObj({
        'f': 0,
        'x': 0,
        'y': 0,
        'text': title,
        'fg': fgColor,
        'bg': bgColor,
    })

def drawText(x, y, text, fgColor=COLOR_WHITE, bgColor=COLOR_BLACK, fl = 0):
    writeObj({
        'f': 0 + fl,
        'x': x,
        'y': y,
        'text': text,
        'fg': fgColor,
        'bg': bgColor,
    })

def drawImage(x, y, path):
    writeObj({
        'f': 0,
        'x': x,
        'y': y,
        'image': path,
    })


if __name__ == '__main__':
    drawText(0, 0, """LCD模块测试""")